<?php

namespace PhpQq\WebQq;

/**
 * 发送qq消息
 */
class MessageSender extends \Thread {

    private $messageid;
    private $cookie;
    private $outbox;
    private $inbox;
    private $messageExec;
    private $retry;
    private $shutdown = false;

    public function __construct() {
        $this->messageid = mt_rand(10000000, 90000000);
        $this->cookie = SavedSession::$cookie;
        $this->outbox = MessageQueue::getInstance()->getOutbox();
        $this->inbox = MessageQueue::getInstance()->getInbox();
        $this->messageExec = MessageQueue::getInstance()->messageExec();
        $this->retry = new \Threaded;
        WebCurl::init();
        SavedSession::init();
        Message::init();
    }

    public function run() {
        $curl = new WebCurl();
        while (true) {
            while (count($this->inbox) > 0) {
                $serialized = $this->inbox->shift();
                $message = unserialize($serialized);
                $div = 250;
                $lenth = mb_strlen($message['content']);
                $payload = [];
                $count = (int) ($lenth / $div);
                
                for ($i = 0; $i <= $count; $i++) {
                    $oneline = mb_substr($message['content'], 0, $div);
                    $message['content'] = str_replace($oneline, '', $message['content']);
                    $payload[] = $oneline;
                }
                
                
                foreach ($payload as $oneline) {
                    echo $oneline;
                    $msg = $message;
                    $msg['content'] = $oneline;
                    if ($message['type'] == Message::USER) {
                        
                        foreach($this->messageExec['message'] as $key=>$exec)
                        {
                            $msgStatus = $this->messageExec['message'][$key]->exec($msg);
                            if($msgStatus === true)
                            {
                                break;
                            }
                            else if($msgStatus === false)
                            {
                                continue;
                            }
                            else if(mb_strlen($msgStatus) > 0)
                            {
                                if ($this->sendUser($curl, $message['from'], $msgStatus) === false) {
                                    return 'send message is ok'.$oneline;
                                }
                            }
                        }
                    } elseif ($message['type'] == Message::GROUP) {
                        
                        foreach($this->messageExec['message'] as $key=>$exec)
                        {
                            $msgStatus = $this->messageExec['message'][$key]->exec($msg);
                            if($msgStatus === true)
                            {
                                break;
                            }
                            else if($msgStatus === false)
                            {
                                continue;
                            }
                            else if(mb_strlen($msgStatus) > 0)
                            {
                                if ($this->sendGroup($curl, $message['from'], $msgStatus) === false) {
                                    return 'send message is ok'.$oneline;
                                }
                            }
                        }
                    }
                }
            }

            $list = count($this->outbox);
            if ($list < 1)
                $list = 1;
            if ($list > 1000000)
                $list = 10000;
            $sleep = (int) (1000000 / $list);
            usleep($sleep);
        }
    }

    private function sendUser($curl, $uin, $content) {
        $this->messageid++;
        $json = $curl->
                setUrl('http://d1.web2.qq.com/channel/send_buddy_msg2')->
                setReferer('http://d1.web2.qq.com/proxy.html?v=20151105001')->
                setPost([
                    'r' => json_encode([
                        'to' => $uin,
                        'content' => '["' . $content . '",["font",{"name":"宋体","size":10,"style":[0,0,0],"color":"000000"}]]',
                        'face' => 603,
                        'clientid' => SavedSession::$clientid,
                        'msg_id' => $this->messageid,
                        'psessionid' => SavedSession::$psessionid,
                            ], JSON_FORCE_OBJECT)
                ])->
                setCookie($this->cookie)->
                returnHeader(false)->
                setTimeOut(5)->
                exec();
        $json = json_decode($json, true);
        if (!is_array($json)) {
            return false;
        }
        if (isset($json['retcode']) && $json['retcode'] == '1202') {
            Logger::alert('消息被服务器拒绝，请检查是否发送过快或session被系统超时注销');
        }
        return true;
    }

    private function sendGroup($curl, $uin, $content) {
        $this->messageid++;
        $json = $curl->
                setUrl('http://d1.web2.qq.com/channel/send_qun_msg2')->
                setReferer('http://d1.web2.qq.com/proxy.html?v=20151105001')->
                setPost([
                    'r' => json_encode([
                        'group_uin' => $uin,
                        'content' => '["' . $content . '",["font",{"name":"宋体","size":10,"style":[0,0,0],"color":"000000"}]]',
                        'face' => 603,
                        'clientid' => SavedSession::$clientid,
                        'msg_id' => $this->messageid,
                        'psessionid' => SavedSession::$psessionid,
                            ], JSON_FORCE_OBJECT)
                ])->
                setCookie($this->cookie)->
                returnHeader(false)->
                setTimeOut(5)->
                exec();
        $json = json_decode($json, true);
        if (!is_array($json)) {
            return false;
        }
        if (isset($json['retcode']) && $json['retcode'] == '1202') {
            Logger::alert('消息被服务器拒绝，请检查是否发送过快或session被系统超时注销');
        }
        return true;
    }

    public function shutdown() {
        $this->shutdown = true;
    }

}
